$(function () {
    var query = {}, fields = 'id|name|pickupTime|htTime|isFilling|shortName|admin|fee|address|showDriver|phone|fax|order|remark',

        $search = $('.search'), $searchBar = $('.search-btn');
    var config = {
        users: '/user/query?size=150',
        coloum_num: 8, //列数目
        query: '/store/query?',//分页查询URL,
        create: '/store/create',//create,
        update: '/store/update',
        plus: '/store/plus',
        minus: '/store/minus',
        'delete': '/store/delete',
    };
    $searchBar.click(function () {
        $(this).button('loading');
        search({keyword: $search.val()});
    });
    function search(obj,isForce) {
        var query_ = {};
        $.extend(query_, query, obj instanceof Object ? obj : {});
        $loading.fadeIn();
        if (!isForce) {
            if (isSameQueryStr(query_, query)) { //查询条件和上次一样，取消请求
                return $loading.fadeOut();
            }
        }
        var arg = [];
        Object.keys(query_).map(function (key) {
            arg.push(key + '=' + query_[key])
        });
        query  = query_;
        $.get(config.query + arg.join('&'), function (res) {
            $searchBar.button('reset');
            if (res.list.length) {
                render(res.list)
            } else {
                render(noData(config.coloum_num));
                $('.reset-query').click(function () {
                    $search.val('');
                    $searchBar.click();
                })
            }
            var page = res.page;
            pageInit(page,query,search);


        });
    }

    function render(list) {
        // $('.table-responsive .table tbody')

        $('.table-responsive .table tbody').html('');
        if (list instanceof Array) {
            list.forEach(function (item, index) {
                // re
                $('.table-responsive .table tbody')
                    .append('<tr> \
                    <td scope="row">' + (index + 1) + '</td> \
                <td>' + item.name + '</td> \
                <td>' + item.phone + '</td> \
                <td>' + item.fax + '</td> \
                <td>' + (item.showDriver == '0' ? "不显示" : "显示") + '</td> \
                <td>' + item.order + '</td> \
                <td>' + (item.fee || '未设置') + '</td> \
                <td>' + (item.numberCanSend || '0') + '</td> \
                <td>' + (item.numberCanSell || '0') + '</td> \
                <td>' + (item.address) + '</td> \
                <td>' + item.shortName + '</td> \
                <td>' + (item.isFilling||'-') + '</td> \
                <td>' + (item.pickupTime||'-') + '</td> \
                <td>' + (item.htTime||'-') + '</td> \
                <td>' + (item.code||'-') + '</td> \
            <td class="text-right" style="width: 56px;padding: 1px 15px;"> \
                <div class="btn-group" role="group" aria-label="..." style="width: 40px;"> '
                        + '<div class="operate-area" style="right:-1px;">' +
                        '<button type="button" class="btn btn-xs  btn-danger opt-delete"   data-loading-text="删除.." data-json=\'' + JSON.stringify(item) + '\'>删除</button>' +
                        '<button type="button" class="btn btn-xs  btn-default interactive opt-update" data-json=\'' + JSON.stringify(item) + '\' data-toggle="modal" data-target=" .add-user-modal-lg">修改</button>' +
                        '<button type="button" data-id="' + item.id + '" class="btn btn-xs btn-info opt-add">增加库存</button> ' +
                        '</div>' +
                        '<button type="button" class="btn btn-xs btn-primary opt-detail">更多</button> \
                        </div> \
                        </td> \
                        </tr>')
            });
            $('.opt-add').click(function () {
                var self = this;
                var $alertCreateLabingBill = $.alert({
                    title: '增加库存 ',
                    hasfoot: false,
                    width: 'normal',
                    body: $('#lading-bill-actual-template').html(),
                    shown: function () {
                        var btnCreateLadingBill = $('.btn-update-actual');
                        $(".btn-update-actual-lading-bill").validate({
                            submitHandler: function (form_) {
                                btnCreateLadingBill.button('loading');
                                var form = {};
                                var ladingBillFields = 'actual';
                                ladingBillFields.split('|').map(function (item) {
                                    form[item] = form_[item].value
                                });
                                form['id'] = $(self).data('id');
                                form['number'] = form['actual'];
                                $.post(config.plus, form, function (xhr, data) {
                                    if (xhr.code == 200) {
                                        search({},true);
                                        $alertCreateLabingBill.modal('hide');
                                    } else {
                                        alert(xhr.error)
                                    }
                                    btnCreateLadingBill.button('reset');
                                });
                                return false;
                            }
                        });
                    },
                })
            });
            $('.opt-detail').click(function () {
                var self = this;
                $(this).siblings('.operate-area').toggle();
            });
            $('.opt-update').click(function () {
                $(this).closest('tr').addClass('active').siblings('tr').removeClass('active');
                var item = $(this).data('json');
                fields.split('|').map(function (key) {
                    var $item = $('[name=' + key + ']');
                    if ($item[0].type == 'checkbox') {
                        $('[name=' + key + ']').attr('checked', true)
                    } else {
                        $item.val(item[key]);
                    }
                });
                disableBtn($('[name=name]'));
            });
            $('.opt-delete').click(function () {
                $(this).closest('tr').addClass('active').siblings('tr').removeClass('active');
                var self = this;
                $(this).button('loading');

                var item = $(this).data('json');
                if (confirm('确认删除？')) {
                    $.post(config['delete'], {id: item.id}, function (xhr, data) {
                        $(self).button('reset');
                        if(xhr.code==200){
                            $(self).closest('tr').remove()
                        }else {
                            alert(xhr.error);
                        }

                    });
                } else {
                    $(self).button('reset');
                }
            });
        } else {
            $('.table-responsive .table tbody').html(list);
        }
        $loading.fadeOut();
    }

    search({},true);
    $.when(parent.window.getDataByUrl(config.users,"users"))
        .then(function (users) {
            users.map(function (item) {
                $('[name=admin]').append('<option value="'+item.id+'">'+item.name+'</option>')
            });
            $('[name="admin"]')
                .selectpicker({
                    liveSearch: true,
                });
        });

    // 表单提交
    var $submit = $('#submit');

    $("#user-form").validate({
        submitHandler: function (form_) {

            $submit.button('loading');
            var form = {};
            fields.split('|').map(function (item) {
                if (form_[item].type === 'checkbox') {
                    form[item] = $(form_[item]).is(':checked') ? '1' : '0';
                } else {
                    form[item] = form_[item].value
                }
            });
            var url = config.create;
            if (form.id) { // is update?
                url = config.update;
            } else {
                delete form.id;
            }
            $.post(url, form, function (xhr, data) {
                if (xhr.code == 200) {
                    search({},true);
                    $('.add-user-modal-lg').modal('hide')
                } else {
                    alert(xhr.error)
                }
                $submit.button('reset');
            });
            return false;
        }
    });
    $('.table th .fa').click(function (e) {
        var sort = {sortField: '', sortOrder: ''};
        sort.sortField = $(this).data('sort');
        if ($(this).hasClass('fa-sort') || $(this).hasClass('fa-sort-desc')) {
            sort.sortOrder = 'ASC';
            $(this)
                .removeClass('fa-sort-desc fa-sort')
                .addClass('fa-sort-asc');
            $(this)
                .closest('th')
                .siblings('th')
                .find('.fa')
                .removeClass('fa-sort-desc fa-sort-asc')
                .addClass('fa-sort');
        } else if ($(this).hasClass('fa-sort-asc')) { //asc
            sort.sortOrder = 'DESC';
            $(this)
                .removeClass('fa-sort-asc fa-sort')
                .addClass('fa-sort-desc');
            $(this)
                .closest('th')
                .siblings('th')
                .find('.fa')
                .removeClass('fa-sort-desc fa-sort-asc')
                .addClass('fa-sort')
        }
        search(sort);
    })
});